package com.example.mvvm.data

import com.example.mvvm.data.db.PlaceDao
import com.example.mvvm.data.network.CoolWeatherNetwork
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/*
本地仓库，所有的数据都是从这里取
 */
class PlaceRepository private constructor(
    private val paceDoa: PlaceDao,
    private val network: CoolWeatherNetwork
) {
    suspend fun getProviceList() = withContext(Dispatchers.IO) {
        var list = paceDoa.getProvinceList()
        if (list.isEmpty()) {
            list = network.fetchProvinceList()
            paceDoa.saveProviceList(list)
        }
        list
    }

    suspend fun getCityList(provinceId: Int) = withContext(Dispatchers.IO) {
        var list = paceDoa.getCityList(provinceId)
        if (list.isEmpty()) {
            list = network.fetchCityList(provinceId)
            list.forEach { it.provinceId = provinceId }
            paceDoa.saveCityList(list)
        }
        list
    }

    suspend fun getCountryList(provinceId: Int, cityId: Int) = withContext(Dispatchers.IO) {
        var list = paceDoa.getCountry()
        if (list.isEmpty()) {
            list = network.fetchCountyList(provinceId, cityId)
            list.forEach { it.cityId = cityId }
            paceDoa.saveCountry(list)
        }
        list
    }

    /*
    companion object 修饰为伴生对象,伴生对象在类中只能存在一个，类似于java中的静态方法 Java 中使用类访问静态成员，静态方法
     */
    companion object {

        private var instance: PlaceRepository? = null

        fun getInstance(placeDao: PlaceDao, network: CoolWeatherNetwork): PlaceRepository {
            if (instance == null) {
                synchronized(PlaceRepository::class.java) {
                    if (instance == null) {
                        instance = PlaceRepository(placeDao, network)
                    }
                }
            }
            return instance!!
        }

    }

    /*
    !!双感叹号表示如果为空，就抛出异常
    ？如果表示为空，继续走下去
     */
}